const Fs = require('fs');
const Cp = require('child_process');
const Os = require('os');
const Utils = require('./utils.js');

const buildPath = './android/app/src/main/assets/apps/H56086A71/www';

const buildVue = async () => {
  console.log('\x1B[32m%s\x1B[0m', 'vue打包中...');
  return new Promise((resolve, reject) => {
    Cp.exec('vue-cli-service build', null, err => {
      if (!err) {
        console.log('\x1B[32m%s\x1B[0m', 'vue打包完成');
        Fs.copyFileSync('./manifest.json', './dist/manifest.json');
        Utils.copyFile('./dist', buildPath);
        resolve('vue打包完成');
      } else {
        console.log('\x1B[31m%s\x1B[0m', `vue打包失败${err}`);
        reject(new Error(`vue打包失败${err}`));
      }
    });
  });
};

const buildApk = async () => {
  console.log('\x1B[32m%s\x1B[0m', 'apk打包中');
  let command = '';

  if (Os.type() === 'Windows_NT') {
    command = 'cd android && gradlew clean && gradlew assembleRelease && cd ..';
  } else {
    command = 'cd android && ./gradlew clean && ./gradlew assembleRelease && cd ..';
  }

  return new Promise((resolve, reject) => {
    Cp.exec(command, null, err => {
      if (!err) {
        console.log('\x1B[32m%s\x1B[0m', 'apk打包完成');
        resolve('apk打包完成');
      } else {
        console.log('\x1B[31m%s\x1B[0m', `apk打包失败：${err}`);
        reject(new Error(`apk打包失败：${err}`));
      }
    });
  });
};

const removeAssets = async () => {
  return new Promise(resolve => {
    if (Fs.existsSync(buildPath)) {
      Utils.deleteFile(buildPath);
      console.log('\x1B[32m%s\x1B[0m', '删除android本地资源成功');
    }
    resolve('删除android本地资源成功');
  });
};

const init = async () => {
  await removeAssets();
  await buildVue();
  await buildApk();
};

init();

process.on('unhandledRejection', (reason, promise) => {
  console.log('\x1B[31m%s\x1B[0m', '未处理的拒绝：', promise, '原因：', reason);
  process.exit(1);
});
